function isVehicleNumber(vehicleNumber: string) {
    let result = false;
    const express = /^([京津晋冀蒙辽吉黑沪苏浙皖闽赣鲁豫鄂湘粤桂琼渝川贵云藏陕甘青宁新][ABCDEFGHJKLMNPQRSTUVWXY][1-9DF][1-9ABCDEFGHJKLMNPQRSTUVWXYZ]\d{3}[1-9DF]|[京津晋冀蒙辽吉黑沪苏浙皖闽赣鲁豫鄂湘粤桂琼渝川贵云藏陕甘青宁新][ABCDEFGHJKLMNPQRSTUVWXY][\dABCDEFGHJKLNMxPQRSTUVWXYZ]{5,6})$/;
    result = express.test(vehicleNumber);
    return result;
}

function sleep(time: number) {
    return new Promise((resolve) => setTimeout(resolve, time));
}

function inttohex(num: any, size: any) {
    var str, len;
    str = num.toString(16);
    len = str.length;
    if (len >= size) {
        str = str.substr(len - size, size);
    } else {
        while (size > len++) str = '0' + str;
    }
    return str.toUpperCase();
}

function rehextoint(string: any) {
    var i, str, len;
    str = '';
    for (i = 0; i < 16; i += 2) {
        str += string.substr(14 - i, 2);
    }
    return parseInt(str, 16);
}

function GetCRCString(crcdatastr: any, crcinitstr: any) {
    var i, crc, len;
    len = crcdatastr.length * 4;
    for (i = 0; i < (4 - len / 4); i++) {
        crcdatastr += "0"; //!<补 0
    }
    crc = rehextoint(crcdatastr) ^ parseInt(crcinitstr, 16);
    crc &= (1 << 16) - 1;
    for (i = 0; i < len; i++) {
        if (crc & 1) {
            crc >>>= 1;
            crc ^= parseInt(("A001"), 16);
            crc |= (1 << 15);
        } else {
            crc >>>= 1;
        }
    }
    crc &= (1 << 16) - 1;
    return inttohex(crc, 4);
}

function HexStringFormat(str: any) {
    var patrn = /[0-9a-fA-F]/;
    var i, ptr, ch;
    ptr = "";
    for (i = 0; i < str.length; i++) {
        ch = str.substr(i, 1);
        if (patrn.test(ch)) {
            ptr += ch;
        }
    }
    return ptr.toUpperCase();
}

function crc(text: string) {
    var i, str, strcrc;
    if (text.length > 0) {
        strcrc = "0000"; //!<初值
        str = HexStringFormat(text);
        for (i = 0; i < str.length; i += 4) {
            strcrc = GetCRCString(str.substr(i, 4), strcrc);
        }
        return inttohex((parseInt(strcrc, 16) ^ parseInt(("0000"), 16)), 4);
    }
}

function chk8xor(nums: []) {
    let num = 0;
    for (let i = 0; i < nums.length; i++) {
        num ^= nums[i]
    }
    return num
}

function crc16Modbus(data: Uint8Array) {
    let crc = 0xFFFF;
    const poly = 0xA001;

    for (let i = 0; i < data.length; i++) {
        crc ^= data[i];
        for (let j = 0; j < 8; j++) {
            if (crc & 1) {
                crc = (crc >> 1) ^ poly;
            } else {
                crc >>= 1;
            }
        }
    }

    return [(crc & 0xFF00) >> 8, crc & 0x00FF];
}

export default {isVehicleNumber, sleep, crc, chk8xor, crc16Modbus}